package com.suse.warmstill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.suse.warmstill.common.enums.ResponseEnum;
import com.suse.warmstill.common.exception.BusinessException;
import com.suse.warmstill.entity.TbUser;
import com.suse.warmstill.entity.TbUserinfo;
import com.suse.warmstill.mapper.TbUserMapper;
import com.suse.warmstill.mapper.TbUserinfoMapper;
import com.suse.warmstill.service.CosService;
import com.suse.warmstill.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author 黄靖
 * @author 2022-11-05 09:44
 * description:
 **/
@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private CosService cosService;

    @Resource
    private TbUserinfoMapper userinfoMapper;

    @Resource
    private TbUserMapper userMapper;


    @Override
    public String upload(Long userId, MultipartFile file) {
        final TbUserinfo tbUserinfo = userinfoMapper.selectOne(new LambdaQueryWrapper<TbUserinfo>().eq(TbUserinfo::getUserId, userId));
        if (ObjectUtils.isEmpty(tbUserinfo)) {
            throw new BusinessException(ResponseEnum.NO_OBJECT.getCode(), "系统无此用户信息");
        }

        final String photoAdress = cosService.uoloadFile(file);
        tbUserinfo.setPhotoPath(photoAdress);
        userinfoMapper.updateById(tbUserinfo);
        return userinfoMapper.selectOne(new LambdaQueryWrapper<TbUserinfo>().eq(TbUserinfo::getUserId, userId)).getPhotoPath();

    }

    @Override
    public TbUserinfo getUserInfo(Long id) {
        final TbUserinfo tbUserinfo = userinfoMapper.selectOne(new LambdaQueryWrapper<TbUserinfo>().eq(TbUserinfo::getUserId, id));
        if (ObjectUtils.isEmpty(tbUserinfo)) {
            throw new BusinessException(ResponseEnum.NO_OBJECT.getCode(), "系统无此用户信息");
        } else {
            return tbUserinfo;
        }

    }

    @Override
    public void update(TbUserinfo userinfo) {
        final TbUser user = new TbUser();
        user.setUsername(userinfo.getNickName());

        user.setId(userinfo.getUserId());
        final int i = userMapper.updateById(user);

        userinfoMapper.update(userinfo, new LambdaQueryWrapper<TbUserinfo>().eq(TbUserinfo::getUserId, userinfo.getUserId()));
    }
}
